<?php

namespace app\api\model\service;

use think\Model;
class SkillTime extends Model
{
    // 表名
    protected $name = 'service_skill_time';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取服务人员最近时间
     * @param $id
     * @return float|mixed|string
     */
    public static function getSkillTime($id)
    {
        $time = self::where(['skill_id'=>$id,'state'=>0,'starttime'=>['>=',time()+1800]])
            ->order('starttime asc')
            ->value('starttime');
        return $time;
    }

    public static function getSettleTime($id)
    {
        $time = self::where(['skill_id'=>$id,'state'=>0,'starttime'=>['>=',time()+1800]])
            ->order('starttime asc')
            ->field('id,starttime')
            ->find();
        return $time;
    }


    /**
     * 服务者更新时间状态
     * @param $ids
     * @param $skill_id
     * @param $type
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function updateTime($ids,$skill_id,$type='busy')
    {
        $idArr = explode(',',$ids);
        if(!$idArr)
        {
            return false;
        }
        foreach ($idArr as $val){
            $info = self::where(['skill_id'=>$skill_id,'id'=>$val])->field('id,state')->find();
            if($info)
            {
                if($type == 'busy' && $info['state'] != 0){
                    continue;
                }elseif($type == 'recover' && in_array($info['state'],[0,1])){
                    continue;
                }
                $state = $type == 'busy'?2:0;
                self::where(['id'=>$val])->update(['state'=>$state]);
            }
        }
        return true;
    }

    /**
     * 更新服务者时间状态
     * @param $params
     * @param $state
     * @return SkillTime
     */
    public static function updateSkillTime($params,$state)
    {

        return self::where(['skill_id'=>$params['skill_id'],'starttime'=>['between',[$params['starttime'],$params['actendtime']]]])->update(['state'=>$state
        ]);

    }

}